﻿// -----------------------------------------------------------------------
// <copyright file="ImageService.cs" company="EPAM Systems">
////Copyright (c) EPAM Systems, 2012. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------

namespace MBOP.Domain.Services
{
	#region Usings

	using MBOP.Core.Entities.Common;
	using MBOP.Core.Interfaces.DataProviders;
	using MBOP.Core.Interfaces.Managers;
	using MBOP.Core.Interfaces.Services;

	#endregion

	/// <summary>
	/// The <see cref="IImageService"/> implementer
	/// which handles image operations.
	/// </summary>
	public class ImageService : IImageService
	{
		#region Constants

		/// <summary>
		/// Represents default mime type for images.
		/// </summary>
		private const string DEFAULT_IMAGE_MIME_TYPE = "image/jpg";

		#endregion

		#region Private Fields

		/// <summary>
		/// Represents the image data provider.
		/// </summary>
		private IImageDataProvider _imageDataProvider;

		/// <summary>
		/// Represents the cache manager.
		/// </summary>
		private ICacheManager _cacheManager;

		#endregion

		#region Constructors

		/// <summary>
		/// Initializes a new instance of the <see cref="ImageService"/> class.
		/// </summary>
		/// <param name="imageDataProvider">The <see cref="IImageDataProvider"/> implementer</param>
		/// <param name="cacheManager">THe <see cref="ICacheManager"/> implementer</param>
		public ImageService(IImageDataProvider imageDataProvider, ICacheManager cacheManager)
		{
			this._imageDataProvider = imageDataProvider;
			this._cacheManager = cacheManager;
		}

		#endregion

		#region IImageService Members

		#region Methods

		/// <summary>
		/// Gets the image.
		/// </summary>
		/// <param name="id">The image id.</param>
		/// <returns>The image.</returns>
		public Image GetImage(string id)
		{
			Image image = null;

			if (this._cacheManager.IsInCache(id))
			{
				image = this._cacheManager.GetItem<Image>(id);
			}
			else
			{
				image = this._imageDataProvider.GetImageByID(id);

				if (image != null)
				{
					this._cacheManager.Add(image.ID,image,true);
				}
			}

			return image;
		}

		/// <summary>
		/// Adds the image
		/// </summary>
		/// <param name="image">The image.</param>
		/// <returns>The image id.</returns>
		public string AddImage(Image image)
		{
			string key = image.ID;

			if (!this._cacheManager.IsInCache(image.ID))
			{
				this._cacheManager.Add(key, image, false);
			}

			return key;
		}

		#endregion

		#endregion
	}
}
